from django.shortcuts import render

# Create your views here.

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Course, CourseSubscription
from .serializer import CourseSerializer, CourseSubscriptionSerializer


class CourseViewSet(viewsets.ModelViewSet):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    @action(detail=True, methods=['post'])
    def subscribe(self, request, pk=None):
        """订阅课程"""
        course = self.get_object()
        user = request.user

        # 检查是否已订阅
        subscription, created = CourseSubscription.objects.get_or_create(
            user=user,
            course=course,
            defaults={'is_active': True}
        )

        if not created and not subscription.is_active:
            subscription.is_active = True
            subscription.save()

        serializer = CourseSubscriptionSerializer(subscription)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=['post'])
    def unsubscribe(self, request, pk=None):
        """取消订阅课程"""
        course = self.get_object()
        user = request.user

        subscription = get_object_or_404(
            CourseSubscription,
            user=user,
            course=course
        )

        subscription.is_active = False
        subscription.save()

        return Response({"detail": "已取消订阅"}, status=status.HTTP_200_OK)


class CourseSubscriptionViewSet(viewsets.ReadOnlyModelViewSet):
    """用户订阅课程列表"""
    serializer_class = CourseSubscriptionSerializer
    queryset = CourseSubscription.objects.all()

    def get_queryset(self):
        return CourseSubscription.objects.filter(
            user=self.request.user,
            is_active=True
        )
